package com.ncloud.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.chnl.service.ChnlService;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.RedisUtils;
import com.ncloud.product.common.Constant;
import com.ncloud.product.entity.ChnlDiscount;
import com.ncloud.product.entity.Discnt;
import com.ncloud.product.entity.DiscntPrice;
import com.ncloud.product.mapper.ChnlDiscountMapper;
import com.ncloud.product.mapper.DiscntMapper;
import com.ncloud.product.service.DiscntCompService;
import com.ncloud.product.service.DiscntService;
import com.ncloud.product.service.ProductService;

@Service
public class DiscntServiceImpl implements DiscntService{
	
	@Autowired
	private DiscntMapper discntMapper;
	@Reference
	private ChnlService chnlService;
	@Autowired
	private ChnlDiscountMapper chnlDiscountMapper;
	@Autowired
	private DiscntCompService compService;
	@Autowired
	private DiscntPriceServiceImpl priceService;
	@Autowired
	private ProductService productService;
	@Autowired
	private RedisUtils redis;
	private static final Long expireTime= 7*24*60*60L;

	@Override
	public JSONArray getDiscntListByProd(JSONObject json) {
		// 判断参数
		if(!json.containsKey("userID")||!json.containsKey("prodId"))
			throw new UserException(ResultEnum.PARAM_ERROR);
		Long userId = json.getLong("userID");
		Long prodId = json.getLong("prodId");
		JSONObject chnl = chnlService.getChnlByUserId(userId);
		List<Discnt> discnts = getDiscntByProdAndChnl(prodId,chnl.getLong("chnlId"));
		JSONArray array = new JSONArray();
		for (Discnt discnt : discnts) {
			JSONObject discntObj = new JSONObject();
			JSONArray comp = compService.getCompCountByDiscnt(discnt.getDiscntId());
			discntObj = JSON.parseObject(JSON.toJSONString(discnt));
			if(Constant.DISCNT_TYPE_FIXNODENUM.equals(discnt.getDiscntType())){
				discntObj.put("compCount", comp);
			}else if(Constant.DISCNT_TYPE_UNFIXNODENUM.equals(discnt.getDiscntType())){
				JSONObject unfix = (JSONObject)comp.get(0);
				unfix.remove("count");
				discntObj.put("compCount", unfix);
			}
			JSONObject feeInfo = getDiscntById(discnt.getDiscntId(),userId);
			discntObj.putAll(feeInfo);
			array.add(discntObj);
		}
		return array;
	}

	@SuppressWarnings("unchecked")
	private List<Discnt> getDiscntByProdAndChnl(Long prodId, Long chnlId) {
		List<Discnt> discnts = new ArrayList<Discnt>();
		if(redis.exists("DISCNT_LIST_PROD_CHNL"+prodId+"_"+chnlId)){
			discnts = (List<Discnt>) redis.get("DISCNT_LIST_PROD_CHNL"+prodId+"_"+chnlId);
		}else {
			discnts = discntMapper.getDiscntListByProd(prodId,chnlId);
			redis.set("DISCNT_LIST_PROD_CHNL"+prodId+"_"+chnlId, discnts, expireTime);
		}
			
		return discnts;
	}

	public JSONObject getDiscntById(Long discntId, Long userId) {
		JSONObject jsonObject = new JSONObject();
		JSONObject chnl = chnlService.getChnlByUserId(userId);
		Long chnlId = -1L;
		if(chnl!=null && !chnl.isEmpty()){
			chnlId = chnl.getLong("chnlId");
		}
		if(redis.exists("DISCNT_INFO_DISCNTID_CHNLID_"+discntId+"_"+chnlId)){
			return (JSONObject) redis.get("DISCNT_INFO_DISCNTID_CHNLID_"+discntId+"_"+chnlId);
		}
		
		Discnt discnt = discntMapper.getDiscntById(discntId);
		if(discnt==null)
			throw new UserException("套餐ID不存在！");
		
		jsonObject = JSON.parseObject(JSON.toJSONString(discnt));
		
		if(!Constant.DISCNT_TYPE_BASEFEE.equals(discnt.getDiscntType())){
			DiscntPrice price = priceService.getDiscntFeeByDiscnt(discnt);
			if(price!=null)
				jsonObject.put("salePrice", price.getFeeValue());
			
			//获取渠道套餐折扣价
			int discount = 100;
			Long minfee = price.getFeeValue();
			if(chnlId!=-1L){
				ChnlDiscount chnlDiscount = chnlDiscountMapper.getDiscountByChnlId(
						chnl.getLong("chnlId"),Constant.CHNL_DISCOUNT_OBJECT_DISCNT,discnt.getDiscntId());
				if(chnlDiscount!=null) {
					
					if(Constant.CHNL_DISCOUNT_TYPE_DISCNT.equals(chnlDiscount.getDiscountType())){
						/*折扣比例*/
						discount = chnlDiscount.getDiscount().intValue();
						minfee = price.getFeeValue()*discount/100;
					}else if(Constant.CHNL_DISCOUNT_TYPE_PRICE.equals(chnlDiscount.getDiscountType())){
						//基础定价模式
						minfee = chnlDiscount.getPrice();
						
					}else{
						//扩展处理
					}
					
				}
//				else{
//					throw  new UserException(ResultEnum.PARAM_ERROR.getCode(),"当前渠道对应的套餐，没有找到对应的优惠信息！{"+chnl.getLong("chnlId")+","+discnt.getDiscntId());
//				}
				jsonObject.put("maxFee", price.getFeeValue());
				jsonObject.put("minFee", minfee);
			}

		}
		redis.set("DISCNT_INFO_DISCNTID_CHNLID_"+discntId+"_"+chnlId, jsonObject, expireTime);
		return jsonObject;
	}
	
	public JSONObject getBaseDiscntByProd(Long prodId) {
		Discnt discnt = discntMapper.getBaseDiscntByProdId(prodId);
		if(discnt==null)
			throw new UserException("套餐ID不存在！");
		return JSON.parseObject(JSON.toJSONString(discnt));
	}
	public JSONObject getBaseDiscntByProd(JSONObject obj) {
		Long prodId = obj.getLong("prodId");
		return getBaseDiscntByProd(prodId);
	}

	@Override
	public JSONObject getDiscntDetailById(JSONObject json) {
		if(!json.containsKey("discntId"))
			throw new UserException(ResultEnum.PARAM_ERROR);
		Long discntId=json.getLong("discntId");
		Long userId = json.getLong("userID");
		
		JSONObject discnt = this.getDiscntById(discntId,userId);
		
		//非基础套餐需要返回构成参数
		if(!Constant.DISCNT_TYPE_BASEFEE.equals(discnt.getString("discntType"))){
			JSONArray comp = compService.getDiscntCompByDiscnt(json);
			discnt.put("comp",comp);
		}
		
		return discnt;
	}

	@Override
	public JSONObject getPriceInfoByDiscnt(JSONObject json) {
		if(!json.containsKey("discntId")){
			throw new UserException("2001","缺少参数");
		}
		Long discntId = json.getLong("discntId");
		Discnt discnt = discntMapper.getDiscntById(discntId);
		json.put("prodId", discnt.getProdId());
		JSONObject jsonObject = productService.getProdPriceInfo(json);
		return jsonObject;
	}

}
